/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
  <div style="border:0px solid white;padding:0px;">
    <el-table :data="newPatternList" :max-height="tableHeight" id="footerBtn">
      <el-table-column type="expand">
        <template slot-scope="scope">
          <div class="components-container board">
            <Kanban v-for="n in scope.row.ringCount"
                    :key="n"
                    class="kanban todo"
                    :list="scope.row.rings[n-1]"
                    :header-text="'环 '+n"
                    :index="scope.$index"
                    @fatherMethod="fatherMethod"/>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="No" width="45" minWidth="40">
        <template slot-scope="scope">
          <span>{{scope.$index+1}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('openatc.greenwaveoptimize.deviceid')" width="100" minWidth="40">
        <template slot-scope="scope">
          <span>{{scope.row.agentid}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('openatc.greenwaveoptimize.pattern')" width="150" prop="desc">
        <!-- <template slot-scope="scope">
          <el-input size="small" v-model="scope.row.desc"></el-input>
        </template> -->
        <template slot-scope="scope">
          <el-select
           v-model="scope.row.desc"
           size="small"
           :loading="loading"
           @focus="getCurPattern(scope.row.agentid)"
           @change="changeCurPattern(scope.row,$event)">
              <el-option v-for="option in (scope.row.allPatterns)"
                         :key="option.patternid"
                         :label="option.patterndesc"
                         :value="option.patternid">
                <span>{{ option.patterndesc }}</span>
              </el-option>
          </el-select>
          <span></span>
        </template>
      </el-table-column>
      <el-table-column  align="center" :label="$t('openatc.greenwaveoptimize.offset')" width="180" prop="offset">
        <template slot-scope="scope">
          <!-- <el-input size="small" v-model.number="scope.row.offset"></el-input> -->
          <el-input-number controls-position="right" :min="0" :step="1" v-model.number="scope.row.offset"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('openatc.greenwaveoptimize.cycle')" width="80" prop="cycle">
      </el-table-column>
      <el-table-column align="center" :label="$t('edge.pattern.plan')">
        <template slot-scope="scope">
          <div class="pattern-figure">
            <pattern-list
              :patternStatusList="scope.row.rings"
              :cycles="scope.row.cycle"
              :phaseList="scope.row.currPhase"
            >
            </pattern-list>
            </div>
         </template>
      </el-table-column>
      <el-table-column v-if="isShowOperation" align="center" width="80px" :label="$t('edge.pattern.operation')">
        <template slot-scope="scope">
          <el-button type="text"  @click="handleDelete(scope.$index, scope.row)">{{$t('edge.common.delete')}}</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { getPatternList, getTscPhase } from '../../../api/route'
import AreaApi from '../../../api/area'
import { getMessageByCode } from '../../../utils/responseMessage'
import Kanban from '../../../components/Kanban/index.vue'
export default {
  name: 'AreaPatterntable',
  components: {
    Kanban
  },
  props: {
    areaId: {
      type: Number
    },
    isShowOperation: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      loading: false,
      tableHeight: 460,
      screenHeight: window.innerHeight, // 屏幕高度
      newPatternList: []
    }
  },
  created () {
  },
  mounted: function () {
    var _this = this
    _this.$nextTick(function () {
      // window.innerHeight:浏览器的可用高度
      // this.$refs.table.$el.offsetTop：表格距离浏览器的高度
      // 后面的50：根据需求空出的高度，自行调整
      _this.tableHeight =
                window.innerHeight -
                document.querySelector('#footerBtn').offsetTop -
                50
      window.onresize = function () {
        // 定义窗口大小变更通知事件
        _this.screenHeight = window.innerHeight // 窗口高度
      }
    })
  },
  watch: {
    screenHeight: function () {
      // 监听屏幕高度变化
      this.tableHeight =
                window.innerHeight -
                document.querySelector('#footerBtn').offsetTop -
                50
    },
    newPatternList: {
      handler: function (val) {
        this.$emit('onNewPatternListChange', val)
      },
      deep: true
    }
  },
  methods: {
    changeCurPattern (row, curPatternid) {
      // 修改当前方案（allPatterns： 所有可选项）
      const data = {
        agentid: row.agentid,
        patternid: curPatternid,
        patterndes: row.allPatterns.filter(ele => ele.patternid === curPatternid)[0].patterndes,
        allPatterns: row.allPatterns
      }
      row.patternid = data.patternid
      let selectPattern = row.allPatterns.filter(item => item.id === row.patternid)[0]
      let res = this.getRings(selectPattern.rings, row.phaseList)
      row.rings = res.rings
      row.ringCount = res.ringCount
      // row.rings = selectPattern.rings
      row.cycle = selectPattern.cycle
      row.offset = selectPattern.offset
      row.currPhase = row.phaseList
      // this.$emit('changeData', data)
    },
    getTscPhase (agentid) {
      getTscPhase(agentid).then(res => {
        if (!res.data.success) {
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        this.newPatternList.forEach(ele => {
          if (ele.agentid === agentid) {
            ele.phaseList = res.data.data.data.phaseList
          }
        })
      })
    },
    getCurPattern (agentid) {
      // 获取当前设备所有可选方案
      this.loading = true
      getPatternList(agentid).then(res => {
        this.loading = false
        if (!res.data.success) {
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          // return
        }
      })
      this.getTscPhase(agentid)
    },
    doleDelete () {
      let fullList = this.newPatternList.filter(item => item.agentid !== this.chooseId)
      let idList = fullList.map(item => item.agentid)
      let reqData = {
        id: this.areaId,
        list: idList
      }
      AreaApi.updateAreaDevs(reqData).then(res => {
        if (!res.data.success) {
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        this.deleteDiologVisible = false
        this.resetChooseId()
        this.newPatternList = fullList
        this.$message({
          message: this.$t('openatc.common.deletesuccess'),
          type: 'success',
          duration: 1 * 1000,
          onClose: () => {
            // this.$emit('refresh')
          }
        })
      })
    },
    resetChooseId () {
      // 重置为未选择状态
      this.chooseId = 0
      this.$emit('chooseRoute', this.chooseId)
    },
    handleDelete (index, row) {
      let _this = this
      _this.$confirm(_this.$t('openatc.common.sureToDelete'),
        _this.$t('openatc.faultrecord.confirm'), {
          confirmButtonText: _this.$t('openatc.button.OK'),
          cancelButtonText: _this.$t('openatc.button.Cancel'),
          type: 'warning'
        }).then(() => {
        this.chooseId = row.agentid
        this.doleDelete()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('openatc.common.deletecancel')
        })
      })
    },
    onPatternTable (routeData, patternList, phaseList) {
      if (patternList.length === 0) {
        // this.$message.error('方案为空！')
        return
      }
      if (phaseList.length === 0) {
        // this.$message.error('相位为空！')
        return
      }
      this.handlePatternList(routeData, patternList, phaseList)
    },
    getRings (ringsList, phaseList) {
      let res = {}
      let rings = JSON.parse(JSON.stringify(ringsList))
      let count = []
      // 计算有几个环
      for (let ring of rings) {
        if (ring.length === 0) continue
        for (let rr of ring) {
          rr.desc = []
          let direction = phaseList.filter(curp => curp.id === rr.id)[0].direction // 相位方向集合
          let phaseRing = phaseList.filter(curp => curp.id === rr.id)[0].ring
          count.push(phaseRing)
          for (let dir of direction) {
            let obj = {}
            obj.id = dir
            rr.desc.push(obj)
          }
        }
      }
      let ringCount = Array.from(new Set(count)) // 去除数组重复的元素
      ringCount = ringCount.sort(this.sortNumbers) // 把数组中的值按照从小到大的顺序重新排序
      res = {
        rings: rings,
        ringCount: ringCount
      }
      return res
    },
    handlePatternList (routeData, patternList, phaseList) {
      this.newPatternList = []
      let devs = routeData
      for (let dev of devs) {
        let agentid = dev.agentid
        for (let pattern of patternList) {
          let id = pattern.agentid
          if (agentid === id) {
            let obj = {}
            obj = JSON.parse(JSON.stringify(dev))
            obj.agentid = id
            let count = [] // 计算相位有几个环
            if (pattern.feature !== undefined && pattern.feature.patternList.length !== 0) {
              let currPatternList = pattern.feature.patternList
              let patternId = dev.patternid
              if (!patternId) {
                patternId = pattern.feature.patternList[0].id
              }
              let currPattern
              if (Array.isArray(currPatternList)) {
                currPattern = currPatternList.filter(cpl => cpl.id === patternId)[0]
              } else {
                currPattern = currPatternList
              }
              // let currPattern = currPatternList.filter(cpl => cpl.id === patternId)[0]
              if (currPattern.desc === '') {
                obj.desc = this.$t('openatc.greenwaveoptimize.pattern') + currPattern.id
              } else {
                obj.desc = currPattern.desc
              }
              obj.id = currPattern.id
              obj.offset = currPattern.offset
              obj.cycle = currPattern.cycle
              obj.patternId = currPattern.id
              obj.patternid = currPattern.id
              obj.patterndesc = currPattern.patterndesc ? currPattern.patterndesc : currPattern.desc
              obj.allPatterns = pattern.feature.patternList.map(ele => {
                return {
                  ...ele,
                  patternid: ele.id,
                  patterndes: ele.desc,
                  patterndesc: ele.desc === '' ? `${this.$t('openatc.greenwaveoptimize.pattern')}${ele.id}` : ele.desc
                }
              })
              let rings = currPattern.rings
              let currPhase = phaseList.filter(phl => phl.agentid === id)[0].feature.phaseList
              obj.currPhase = currPhase
              // 计算有几个环
              for (let ring of rings) {
                if (ring.length === 0) continue
                for (let rr of ring) {
                  rr.desc = []
                  let direction = currPhase.filter(curp => curp.id === rr.id)[0].direction // 相位方向集合
                  let phaseRing = currPhase.filter(curp => curp.id === rr.id)[0].ring
                  count.push(phaseRing)
                  for (let dir of direction) {
                    let obj = {}
                    obj.id = dir
                    rr.desc.push(obj)
                  }
                }
              }
              obj.rings = rings
            }
            let ringCount = Array.from(new Set(count)) // 去除数组重复的元素
            ringCount = ringCount.sort(this.sortNumbers) // 把数组中的值按照从小到大的顺序重新排序
            obj.ringCount = ringCount
            this.newPatternList.push(obj)
          }
        }
      }
    },
    sortNumbers (a, b) {
      return a - b
    },
    fatherMethod (val) {
      let index = val.index
      let cycle = val.cycle
      this.newPatternList[index].cycle = cycle
    }
  }
}
</script>

<style lang="scss">
  .board {
    width: 100%;
    margin-left: 10px;
    display: flex;
    justify-content: space-around;
    flex-direction: row;
    align-items: flex-start;
  }
  // .kanban {
  //   &.todo {
  //     .board-column-header {
  //       background: $--color-primary;
  //     }
  //   }
  // }
</style>
